<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>数字变化</title>
  </head>
  <body>
    <div class="">价格: <span class="price">299.00</span>元</div>
    <script>
      const priceDom = document.querySelector(".price");
      function animation(from, to, options) {
        const { duration = 1000, onProgress } = options;
        const dis = to - from; // 需要变化的值
        const speed = dis / duration; // 变化的速度
        const startTime = Date.now();
        let value = from; // 当前值

        function _run() {
          const now = Date.now();
          const time = now - startTime;
          if (time >= duration) {
            value = to;
            onProgress && onProgress(value);
            return;
          }
          const d = time * speed; // 变化的值
          value = from + d;
          onProgress && onProgress(value);
          requestAnimationFrame(_run);
        }
        requestAnimationFrame(_run);
      }
      animation(299, 2999, {
        onProgress: (value) => {
          console.log("...计算过程", value);
          priceDom.textContent = value.toFixed(2);
        },
      });
    </script>
  </body>
</html>
